//
//  StepsCountShareViewController.m
//  安好
//
//  Created by qinlongqing on 14/12/9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "StepsCountShareViewController.h"
#import "AppConfig.h"

@interface StepsCountShareViewController ()<MBProgressHUDDelegate>
{
    MBProgressHUD *HUD;
    
    UIImage *_imageV;
}
@end

@implementation StepsCountShareViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = UIColorFromRGB(0xe7f1f4);

    [self makeNavBar];
    
    self.userPhotoImageView.layer.cornerRadius = 2;
    self.userPhotoImageView.clipsToBounds = YES;
    if ([NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]].length > 0) {//登录
        [self.userPhotoImageView setImageWithURL:[NSURL URLWithString:[[UserManager shareInstance] getUserInfo].avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
    }
    else{
        self.userPhotoImageView.image = [UIImage imageNamed:@"默认头像"];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *todayString = [[dateFormatter stringFromDate:[NSDate date]] substringToIndex:11];
    if ([todayString isEqualToString:self.dateString]) {
        self.currentDateLabel.text = @"今天";
    }
    else{
        self.currentDateLabel.text = self.dateString;
    }
    
    self.totalStepsLabel.text = [NSString stringWithFormat:@"%ld步",self.totalSteps];
    
    [self changeToKilometerWithSteps];

    [self getPercentage];
    
    
//    self.shareBTN.layer.cornerRadius = 3;
//    if (IPHONE5_OR_LATER) {
//        self.shareBTN.frame = CGRectMake(20, 416, 280, 45);
//    }
//    else{
//        self.shareBTN.frame = CGRectMake(20, 346, 280, 45);
//    }
    
    CGFloat space = (kScreenHeight - 64 - 249)/7;
    
    self.userPhotoImageView.frame = CGRectMake((kScreenWidth - self.userPhotoImageView.frame.size.width)/2, space, self.userPhotoImageView.frame.size.width, self.userPhotoImageView.frame.size.height);
    self.currentDateLabel.frame = CGRectMake((kScreenWidth - self.currentDateLabel.frame.size.width)/2, self.userPhotoImageView.frame.origin.y + self.userPhotoImageView.frame.size.height + space, self.currentDateLabel.frame.size.width, self.currentDateLabel.frame.size.height);
    
    self.totalStepsLabel.frame = CGRectMake((kScreenWidth - self.totalStepsLabel.frame.size.width)/2, self.currentDateLabel.frame.origin.y + self.currentDateLabel.frame.size.height + space, self.totalStepsLabel.frame.size.width, self.totalStepsLabel.frame.size.height);
    self.sepImageView.frame = CGRectMake((kScreenWidth - self.sepImageView.frame.size.width)/2, self.totalStepsLabel.frame.origin.y + self.totalStepsLabel.frame.size.height + 8, self.sepImageView.frame.size.width, self.sepImageView.frame.size.height);
    
    self.kilometerLabel.frame = CGRectMake((kScreenWidth - self.kilometerLabel.frame.size.width)/2, self.sepImageView.frame.origin.y + self.sepImageView.frame.size.height + space, self.kilometerLabel.frame.size.width, self.kilometerLabel.frame.size.height);
    self.pingYuLabel.frame = CGRectMake((kScreenWidth - self.pingYuLabel.frame.size.width)/2, self.kilometerLabel.frame.origin.y + self.kilometerLabel.frame.size.height + space, self.pingYuLabel.frame.size.width, self.pingYuLabel.frame.size.height);
    self.shareBTN.frame = CGRectMake((kScreenWidth - self.shareBTN.frame.size.width)/2, self.pingYuLabel.frame.origin.y + self.pingYuLabel.frame.size.height + space, self.shareBTN.frame.size.width, self.shareBTN.frame.size.height);
}

-(void)makeNavBar{
    self.navigationItem.title = @"分享";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

- (void)backBtnclicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)changeToKilometerWithSteps{
    CGFloat totalKilometer = (0.5 * self.totalSteps)/1000;
    self.kilometerLabel.text = [NSString stringWithFormat:@"相当于%.2f公里",totalKilometer];
}

- (void)getPercentage{    
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
        [self showInternetActivityIndicator];
        NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"daytime":[self setNewTime]};
        [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetJiBuPersentURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber * statusNum = [responseObject objectForKey:@"status"];
            NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
            NSString * statusString = [numberFormatter stringFromNumber:statusNum];
            if ([statusString isEqualToString:@"1"]) {
                self.pingYuLabel.text = [NSString stringWithFormat:@"%@今天已打败%@的人,请再接再厉!",[[UserManager shareInstance] getUserInfo].username,[[responseObject valueForKey:@"data"] valueForKey:@"ratio"]];
            }else{
                
            }
            [HUD hide:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            [HUD hide:YES];
        }];
    }
    else{//未登录

    }
}

//- (NSString *)setNewTime{
//    NSDate *now = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
//    int year = [dateComponent year];
//    int month = [dateComponent month];
//    int day = [dateComponent day];
//    
//    NSString *time = [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
//    return time;
//}

- (NSString *)setNewTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[formatter stringFromDate: [NSDate date]];
    return locationString;
    
}


- (void)showInternetActivityIndicator{
    HUD =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.center = self.view.center;
    HUD.dimBackground = NO;
    HUD.delegate = self;
}

- (void)hudWasHidden:(MBProgressHUD *)hud{
#ifdef DEBUGX
    NSLog(@"Remove HUD from screen when the HUD was hidded");
#endif
    [hud removeFromSuperview];
}


- (void)doToShare:(UIButton *)sender{
    CGRect rect = CGRectMake(0, 0, kScreenWidth, sender.frame.origin.y);
//    if (IPHONE5_OR_LATER) {
//        rect = CGRectMake(0, 0, 320, 375);
//    }
//    else{
//        rect = CGRectMake(0, 0, 320, 325);
//    }
    
    [self imageFromView:self.view atFrame:rect];
#pragma 让分享的视图出现，并显示到屏幕的最前方
    [self showShareView];
}
#pragma 截图视图
- (void)imageFromView:(UIView *)theView atFrame:(CGRect)r
{
    UIGraphicsBeginImageContext(theView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGImageRef imageRef = theImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, r);//原图中抠出来部分图
    UIImage *subImage = [UIImage imageWithCGImage:subImageRef];//新图
    _imageV = subImage;
}

#pragma 实现share方法，通过点击的视图的tag值判断是什么类型的分享
- (void)share:(UITapGestureRecognizer *)shareTap{
    switch (shareTap.view.tag) {
        case 11:{//微信
            [self weixinShare:kWeiXinShareUrl :kWeiXinShareTitle :kWeiXinShareText :_imageV];
        }
            break;
        case 12:{//朋友圈
            [self weixinFriendShare:kWeiXinFriendShareUrl :kWeiXinFriendShareTitle :kWeiXinFriendShareText :_imageV];
        }
            break;
        case 13:{//短信
            [self showSMSPicker:kWeiXinFriendShareUrl :kWeiXinFriendShareTitle :kWeiXinFriendShareText :nil];
        }
            break;
        case 14:{//QQ
            [self qqShare:kQQshareUrl :kQQshareTitle :kQQshreDescription :_imageV];
        }
            break;
        case 15:{//QQ空间
            [self qqZoneShare:kQQZoneShareUrl :kQQZoneShareTitle :kQQZoneShareDescription :_imageV];
        }
            break;
        case 16:{//新浪微博
            [self sinaWeiboShare:kSinaWeiboShareUrl :kSinaWeiboShareTitle :kSinaWeiboShareText :_imageV];
        }
            break;
            
        default:
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
